
layui.use(['form', 'layer', 'laydate', 'table', 'upload'], function(){

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        upload = layui.upload,
        table = layui.table;

    var datalist_url = $('.datalist_url').val();
    var add_url = $('.add_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var save_url = $('.save_url').val();
    var get_product_url = $('.get_product_url').val();
    var get_product_url2 = $('.get_product_url2').val();
    var get_productlist_url = $('.get_productlist_url').val();
    var handle_url = $('.handle_url').val();

    //开始日期
    laydate.render({
        elem: '#start_time'
    });
    //结束日期
    laydate.render({
        elem: '#end_time'
    });


    // Table 列表
    var tableIns = table.render({
        elem: '#dataTable',
        url : datalist_url,
        page : true,
        cellMinWidth : 95,
        //height : "full-100",
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "dataTable",

        cols : [[
            /* {type: "checkbox", fixed:"left", width:50},*/
            {field: 'key', title: '序号', width:80, align:"center"},
            {field: 'name', title: '广告名称', minWidth:240},
            {field: 'type', title: '广告形式', minWidth:340,align:'center'},
            {field: 'start_time', title: '开始时间', align:'center', sort: true},
            {field: 'end_time', title: '结束时间', align:'center',  sort: true},
            {field: 'create_date', title: '创建日期', align:'center',  sort: true},
            {field: 'status', title: '启用/禁用', fixed:"right", align:"center", templet:function(data){
                var html = '';
                if (data.status == 1) {
                    html += '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" lay-text="启用|禁用" value="'+data.id+'" checked>';
                } else {
                    html += '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" lay-text="启用|禁用" value="'+data.id+'">';
                }

                return html;
            }},
            /*{title: '操作', minWidth:175, templet:'#handleBar', fixed:"right", align:"center"},*/
            {title: '操作', fixed:"right", align:"center", minWidth:140, templet:function(data){
                var html = '';
                html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                html += '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>';

                return html;
            }}
        ]]
    });

    // 搜索
    $(".search_btn").on("click", function(){

        if ($('.title').val() != ''){
            var name = $('.searchBox').find('input[name=name]').val();
        }

        table.reload("dataTable", {
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                name: name,
            }
        });
    });
    // 搜索
    $(".search_btn01").on("click", function(){

        if ($('.title').val() != ''){
            var name = $('.searchBox').find('input[name=name]').val();
        }

        table.reload("tableList01", {
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                name: name,
            }
        });
    });
    // 搜索
    $(".search_btn02").on("click", function(){

        if ($('.title').val() != ''){
            var name = $('.searchBox').find('input[name=name]').val();
        }

        table.reload("tableList02", {
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                name: name,
            }
        });
    });

    // Status 操作
    form.on('switch(status)', function(data){
        var index = layer.msg('修改中，请稍候',{icon: 16,time:false,shade:0.8});

        var status = 2;
        if(data.elem.checked){
            status = 1;
        }
        $.ajax({
            url: handle_url,
            data: {'id' : data.elem.value,'status' : status},
            type: "post",
            dataType: "json",
            success: function(res){
                top.layer.close(index);
                top.layer.msg(res.msg);
                if (res.code == 1) {
                    parent.layui.table.reload('tableList', {});
                } else {
                    data.elem.checked = !data.elem.checked;
                    form.render();
                }
            },
            error:function(data){
                layer.msg("服务器无响应");
            }
        });
    });

    // 批量删除
    $(".delAll_btn").on("click", function(){
        var checkStatus = table.checkStatus('tableList'),
            data = checkStatus.data,
            ids = [];
        if(data.length > 0) {
            for (var i in data) {
                ids.push(data[i].id);
            }
            layer.confirm('确定删除选中的数据？', {icon: 3, title: '提示信息'}, function (index) {
                $.ajax({
                    url: delete_url,
                    data: {"ids": ids},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('删除成功', {icon: 1});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            })
        }else{
            layer.msg("请选择需要删除的数据");
        }
    });

    $('.add_btn').on('click', function(){
        formHtml();
    });

    // 列表操作
    table.on('tool(dataTable)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        // 删除
        if (layEvent === 'del') {
            layer.confirm('确定删除此数据？',{icon:3, title:'提示信息'},function(index){
                $.ajax({
                    url: delete_url,
                    data: {"id": data.id},
                    type: "POST",
                    dataType: "json",
                    success: function (res) {
                        if (res.code == 1) {
                            layer.msg('已删除', {icon: 1, time: 1000});
                            tableIns.reload();
                            layer.close(index);
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (data) {
                        layer.msg("服务器无响应");
                    }
                });
            });
        } else if(layEvent === 'edit'){

            formHtml(data);
        }
    });

    // Form 表单
    function formHtml(data){
        var content = add_url;

        if(data){
            content = edit_url + '?id=' + data.id;
        }
        // 右侧面板
        var index = layer.open({
            type: 2,
            anim: -1,
            title: false,
            closeBtn: false,
            offset: 'r',
            shade: 0.2,
            //, shadeClose: true // 是否点击遮罩关闭
            skin: 'layui-anim layui-anim-rl layui-layer-adminRight',
            area: '800px',
            top: 0,
            content: content
        });
    }

    // Table 多商品 列表
    var sessionProduct = table.render({
        elem: '#dataTable01',
        url : get_productlist_url,
        page : false,
        cellMinWidth : 95,
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "tableList01",
        cols : [[
            {field: "name", title:"商品名称",align:'center',minWidth:140},
            {field: 'bar_code', title: '条码',align:'center', minWidth:180},
            {field: 'typeName', title: '分类', align:'center', sort: true},
            {field: 'qty', title: '库存',align:'center'},
            {field: 'unit', title: '单位',align:'center', minWidth:80},
            {title: '操作', fixed:"right", align:"center", minWidth:140, templet:function(data){
                var html = '';
                //html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit" href="'+edit_url+'?id='+data.id+'"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                html += '<button type="button" class="layui-btn " lay-event="purchase-add">选取 <input type="text" style="display:none" value="' +
                    ''+data.id+'" name="product_id"></button>'  ;
                return html;
            }}
        ]]
    });

    // 列表操作 多商品
    table.on('tool(dataTable01)', function(obj){
        var layEvent = obj.event,
            data = obj.data;

        // 选取
        if (layEvent == 'purchase-add') {
            var index = parent.layer.getFrameIndex(window.name);
            layer.msg('选择成功', {icon: 1, time: 1000});
            var rule_length =  $('.payment-rule-group').parents('.rule-group').length;
            var $html = '';
            $html += '<div class="layui-form-item layui-form-text rule-group">';
            $html += '<div class="layui-inline">';
            $html += '<label class="layui-form-label">商品名</label>';
            $html += '<div class="layui-input-inline">';
            $html += '<input type="hidden" class="layui-input " name="link_detail_product[]" value="'+data.id+'" maxlength="10" placeholder="元" autocomplete="off">';
            $html += '<div style="line-height: 39px; width: 300px">'+data.name+'</div>';
            $html += '</div>';
            $html += '</div>';
            $html += '<div class="layui-inline">';
            $html += '<div class="layui-input-inline">';
            $html += '<button type="button" class="layui-btn layui-btn-danger delRule-btn"><i class="layui-icon layui-icon-delete"></i></button>';
            $html += '</div>';
            $html += '</div>';

            console.log(getCheckBox($html));
            parent.layer.getChildFrame('.payment-rule-group', 1).append($html);
            layer.close(index);
        }
    });

    //选择优惠商品 多商品
    $('.addPro-btn').on('click', function(){
        top.layer.open({
            type: 2,
            anim: 1,
            title: '选择商品',
            shade: 0.2,
            skin: 'layui-anim layui-anim-rl layui-layer-Elasticframe',
            area: ['900px','700px'],
            content: get_product_url,
            yes:function () {
                sessionProduct.reload();
            }

        });
    });

    // Table 多商品 列表
    var sessionProduct2 = table.render({
        elem: '#dataTable02',
        url : get_productlist_url,
        page : false,
        cellMinWidth : 95,
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "tableList02",
        cols : [[
            {field: "name", title:"商品名称",align:'center',minWidth:140},
            {field: 'bar_code', title: '条码',align:'center', minWidth:180},
            {field: 'typeName', title: '分类', align:'center', sort: true},
            {field: 'qty', title: '库存',align:'center'},
            {field: 'unit', title: '单位',align:'center', minWidth:80},
            {title: '操作', fixed:"right", align:"center", minWidth:140, templet:function(data){
                var html = '';
                //html += '<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit" href="'+edit_url+'?id='+data.id+'"><i class="layui-icon layui-icon-edit"></i>编辑</a>';
                html += '<button type="button" class="layui-btn " lay-event="purchase-add">选取 <input type="text" style="display:none" value="' +
                    ''+data.id+'" name="product_id"></button>'  ;
                return html;
            }}
        ]]
    });

    // 删除商品
    $('.payment-rule-group').on('click', '.delRule-btn', function(){
        $(this).parents('.rule-group').remove();
    });

    //因父子页面等级关系 取消后需刷新页面
    $('.layui-btn-primary').on('click',function(){
        parent.location.reload();
    });

    // 列表操作  单商品
    table.on('tool(dataTable02)', function(obj){
        var layEvent = obj.event,
            data = obj.data;

        // 选取
        if (layEvent == 'purchase-add') {
            console.log(data);
            layer.msg('选择成功', {icon: 1, time: 1000});
            var index = parent.layer.getFrameIndex(window.name);
            $(parent.window.frames[0].document).find('#link_product').val(data.id);
            $(parent.window.frames[0].document).find('#product_name').text(data.name);
            layer.close(index);
        }
    });
    //选择优惠商品 单商品
    $('.addPro2-btn').on('click', function(){
        top.layer.open({
            type: 2,
            anim: 1,
            title: '选择商品',
            shade: 0.2,
            skin: 'layui-anim layui-anim-rl layui-layer-Elasticframe',
            area: ['900px','700px'],
            content: get_product_url2,
            yes:function () {
                sessionProduct2.reload();
            }

        });
    });

    //是否开启专题商品
    form.on('switch(status_detail_product)', function(data){
        if(this.checked){
            $('#status_detail_product').prop('checked',true);
            $('#status_one_product').removeAttr('checked');
            $('#status_link_type').removeAttr('checked');

            $('.status_detail_text').removeClass('layui-hide');
            $('.status_one_text').addClass('layui-hide');
            $('.status_link_text').addClass('layui-hide');
        }else {
            $("#status_detail_product").removeAttr('checked');
            $('.status_detail_text').addClass('layui-hide');
        }
        form.render();
    });
    //是否开启单个商品
    form.on('switch(status_one_product)', function(data){
        if(this.checked){
            $('#status_one_product').prop('checked',true);
            $('#status_detail_product').removeAttr('checked');
            $('#status_link_type').removeAttr('checked');

            $('.status_one_text').removeClass('layui-hide');
            $('.status_detail_text').addClass('layui-hide');
            $('.status_link_text').addClass('layui-hide');
        }else {
            $("#status_one_product").removeAttr('checked');
            $('.status_one_text').addClass('layui-hide');
        }
        form.render();
    });
    //是否开启链接位置
    form.on('switch(status_link_type)', function(data){
        if(this.checked){
            $('#status_link_type').prop('checked',true);
            $('#status_detail_product').removeAttr('checked');
            $('#status_one_product').removeAttr('checked');

            $('.status_link_text').removeClass('layui-hide');
            $('.status_one_text').addClass('layui-hide');
            $('.status_detail_text').addClass('layui-hide');
        }else {
            $("#status_link_type").removeAttr('checked');
            $('.status_link_text').addClass('layui-hide');
        }
        form.render();
    });

    // 文件上传
    upload.render({
        elem: '.linkLogo',
        url: '../../json/linkLogo.json',
        method : "post",
        done: function(res, index, upload){
            var num = parseInt(4*Math.random());  //生成0-4的随机数，随机显示一个头像信息
            $('.linkLogoImg').attr('src',res.data[num].src);
            $('.linkLogo').css("background","#fff");
        }
    });

    //多选商品 验证是否重复选择
    function getCheckBox(str){
          var ha = $(str).find('.layui-form-checked');
          var list = [];
          ha.each(function(){
             if ($(this).hasClass('layui-from-checked')){
                 list.push($(this).prev().val());
             }
          });
          return list;
    };

    // 自定义验证规则
    form.verify({
        coupon_type: function(value){
            if(value == 0){
                return '请选择优惠券类型';
            }

        },
        name: function(value){
            if(value.trim() == ''){
                return '请输入优惠券名称';
            }

        },
        number:function (value) {
            if(value.trim() == ''){
                return '请填写优惠券数量';
            }
            if(!/^[1-9]\d*$/.test(value)){
                return '请输入正确的数量'
            }
        },
        coupon_purpose:function (value) {
            if(value == 0){
                return '请选择优惠券领取途径';
            }
        },

        threshold:function (value) {
            if($("#coupon_type option:selected").val() == 1 || $("#coupon_type option:selected").val() == 2){
                if(value.trim() == ''){
                    return '使用门槛金额必填';
                }
                if(value==0){
                    return '使用门槛金额有误';
                }
                if(!/^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/.test(value)){
                    return '使用门槛金额有误';
                }

            }
        },

        cash_amount:function (value) {
            if($("#coupon_type option:selected").val() == 1 || $("#coupon_type option:selected").val() == 2 || $("#coupon_type option:selected").val() == 3){
                if(value.trim() == ''){
                    return '抵现金额必填';
                }
                if(value==0){
                    return '抵现金额有误';
                }
                if(!/^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/.test(value)){
                    return '抵现金额有误';
                }

            }
        },
        product_id:function (value) {
            if($("#coupon_type option:selected").val() == 3 ||$("#coupon_type option:selected").val() == 6){
                if(value.trim() == ''){
                    return '必须选择商品';
                }
            }
        },
    });

    // 表单提交
    form.on("submit(laySave)", function(data){
        //弹出loading
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});

        $.ajax({
            url: save_url,
            data: data.field,
            type: "post",
            dataType: "json",
            success: function(res){
                top.layer.close(index);
                if(res.code == 1){
                    // var index = parent.layer.getFrameIndex(window.name);
                    // // 关闭当前frame
                    // parent.layer.close(index);

                    layer.closeAll("iframe");
                    //parent.window.tableIns.reload();
                    parent.layui.table.reload('tableList', {});
                    // 刷新父页面
                    parent.location.reload();
                }else {
                    layer.msg(res.msg);
                }
            },
            error:function(data){
                layer.msg("服务器无响应");
            }
        });

    })
});